/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.jsimplemarket.wicket.pages;

import com.googlecode.jsimplemarket.model.Utilizator;
import com.googlecode.jsimplemarket.repository.GenericRestriction;
import com.googlecode.jsimplemarket.security.SpringLoginContext;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.wicket.SecuredWebSession;
import java.util.Date;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.wicketstuff.security.authentication.LoginException;
import org.wicketstuff.security.components.SecureWebPage;
import org.wicketstuff.security.hive.authentication.LoginContext;

/**
 *
 * @author Alexandru.Codescu
 */
public class LoginPage extends WebPage {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginPage.class);
    private String username;
    private String password;
    @SpringBean(name = "genericService")
    private GenericService<Utilizator> genericService;
    
    private Link createNavigationLink(String id, final Class<? extends SecureWebPage> pageClass) {
        Link link = new Link(id) {
            @Override
            public void onClick() {
                setResponsePage(pageClass);
            }
        };
        return link;
    } 

    
    private void creareFormLogin() {
    	
        final Form<LoginPage> form = new Form<LoginPage>("form");
        form.setModel(new CompoundPropertyModel<LoginPage>(this));
        
        final Link homeLink = createNavigationLink("homeLink", PiataViewPage.class);
        final WebMarkupContainer wmc = new WebMarkupContainer("divRedirect");
        wmc.add(homeLink);
        wmc.setVisible(false);
    	form.add(wmc);
        
        form.add(new TextField("username").setRequired(true));
        form.add(new PasswordTextField("password").setRequired(true));
        final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
        form.add(feedbackPanel);
        
        SubmitLink loginButton = new SubmitLink("submit") {

            @Override
            public void onSubmit() {
                LoginContext context = new SpringLoginContext(username, password);
                try {
                    ((SecuredWebSession) getSession()).login(context);
                    GenericRestriction genericRestriction = new GenericRestriction("numeUtilizator", username);
                    Utilizator utilizatorDb = genericService.getSingleResult(Utilizator.class, genericRestriction);
                    //setResponsePage(AdminPage.class);
                    setResponsePage(PiataViewPage.class);
                } catch (LoginException e) {
                    LOGGER.error(e.getMessage(), e);
                    if (e.getCause() == null) {
                        error(LoginPage.this.getString("error.dejaAutentificat"));
                        wmc.setVisible(true);
                    } else if (e.getCause() instanceof AccountStatusException) {
                        error(LoginPage.this.getString("error.contBlocat"));  
                    } else if (e.getCause() instanceof UsernameNotFoundException) {
                        form.error(LoginPage.this.getString("error.credentialeGresite"));
                    } else if (e.getCause() instanceof BadCredentialsException) {
                        form.error(LoginPage.this.getString("error.credentialeGresite"));
                    } else {
                        long cod = new Date().getTime();
                        form.error("Eroare interna la autentificare (cod: " + cod + "). Mai incearca o data!");
                    }
                } finally {
                    // Don't let the password hanging around
                    password = null;
                }
            }
            
        };
        
        form.add(loginButton);
        form.setDefaultButton(loginButton);

        add(form);
    }
    
    public LoginPage() {
    	

        creareFormLogin();
    }
}
